#!/usr/bin/python

import urllib.request
import sys
import time
from datetime import datetime, timedelta
from itertools import islice
from sqlTools import insert

#get Data From Yahoo  save to localfile  
#
def getDataFromYahoo(stockDic):
    sql_insert="insert into stock_detail (exchangeID,codeID,open,high,low,close,volume,date) values"
    sql_insert_parts=''
    
    f=""
    stockID=stockDic["stockID"]
    exchangeID=stockDic["exchangeID"]
    stockCode=stockDic["stockCode"]
    YahooSuffix=stockDic["YahooSuffix"] 
    if YahooSuffix is None:
        f=getStockDetailDataFromYahoo(stockCode)
    else:
        f=getStockDetailDataFromYahoo(stockCode+YahooSuffix)
    
    if f=="2":
        return
    else:
        # if f has one line ,then split len(f)>=3 
        if len(f)>=2:
            date=""
            code_id=stockID
            exchange_id=exchangeID
            open_price=0.0
            high_price=0.0
            low_price=0.0
            close_price=0.0
            volume=0.0
            for line in f[1:]:
                #print(line) 2004-11-08,170.93029,175.440304,169.400298,172.550295,22467400,86.188959
                lineSplit=line.split(',')
                date=lineSplit[0]
                open_price=lineSplit[1]
                high_price=lineSplit[2]
                low_price=lineSplit[3]
                close_price=lineSplit[4]
                volume=lineSplit[5]
                 
                sql_insert_parts=sql_insert_parts+"("+str(exchangeID)+","+str(stockID)+","+str(open_price)+","+str(high_price)+","+str(low_price)+","+str(close_price)+","+str(volume)+",'"+date+"'),"	
        if len(sql_insert_parts)>0:
            sql=sql_insert+sql_insert_parts    
            #print(sql)
            insert(sql[:-1]+";") 


def getStockDetailDataFromYahoo(stockCode):
    #'2016-12-02'
    now = datetime.now()
    begindate=now - timedelta(days=1)

    beginday=begindate.strftime('%d')
    beginmonth=begindate.strftime('%m')
    beginyear=begindate.strftime('%Y')
    #print(beginmonth,beginday,beginyear)
    url2="http://chart.finance.yahoo.com/table.csv?s="+stockCode+"&a="+beginmonth+"&b="+beginday+"&c="+beginyear+"&d="+beginmonth+"&e="+beginday+"&f="+beginyear+"&g=d&ignore=.csv"
    #print(url2)
    url="http://chart.finance.yahoo.com/table.csv?s="+stockCode+"&a=12&b=15&c=2016&d=12&e=15&f=2016&g=d&ignore=.csv"
    print(url)
    dataLists=''
    try:
        dataLists=(urllib.request.urlopen(url).read().decode())[:-2].split('\n')
    except urllib.error.URLError as e:
        print(e.reason)
        return "2"
    return dataLists			
